<?php
class Foto extends AppModel {

	var $name = 'Foto';

	//The Associations below have been created with all possible keys, those that are not needed can be removed
	var $belongsTo = array(
/*
			'User' => array('className' => 'User',
								'foreignKey' => 'user_id',
								'conditions' => '',
								'fields' => '',
								'order' => ''
			),
*/
			'Fotopreview' => array('className' => 'Fotopreview',
								'foreignKey' => 'foto_id',
								'dependent' => true,
								'conditions' => '',
								'fields' => array('id', 'path', 'scale', 'form'),
								'order' => ''
			)
	);
/*
	var $hasMany = array(
			'Fotopreview' => array('className' => 'Fotopreview',
								'foreignKey' => 'foto_id',
								'dependent' => true,
								'conditions' => '',
								'fields' => array('id', 'path', 'scale'),
								'order' => ''
			)
	);
*/

	function getFotos($uid, $scale) {

		if (empty($scale)) {
			$scale = $this->small();
		}

		$conditions['Foto.user_id']		= $uid;
		$conditions['Fotopreview.scale']	= $scale;

		$fields = array('form', 'path', 'id', 'Foto.alt', 'Foto.id', 'Foto.hash');
		//return $this->find('all', array('conditions'=>$conditions , 'fields'=>$fields, 'recursive'=>2, 'order'=>'status DESC'));
		return $this->Fotopreview->find('all', array('conditions' => $conditions , 'fields'=>$fields, 'recursive'=>2, 'order'=>'Foto.status DESC'));
	}

	function getFoto($hash, $scale) {

		if (empty($scale)) {
			$scale = $this->small();
		}

		$fields		= array('id', 'Foto.alt', 'path', 'Foto.hash');

		$conditions['Foto.hash']		= $hash;
		$conditions['Fotopreview.scale']	= $scale;

		if ($hash) {
			return $this->Fotopreview->find('first', array('conditions'=>$conditions, 'fields'=>$fields, 'recursive'=>1));
		}
	}

	function deleteFoto($uid, $hash) {
		$data = false;
		if ($id = $this->field('id', array('user_id'=>$uid, 'hash'=>$hash))) {
			$this->id = $id;
			$data = $this->del();
		}
		return $data;
	}

	function setMainFoto($uid, $hash) {
		$data = false;
		if ($id = $this->field('id', array('user_id'=>$uid, 'hash'=>$hash))) {
			$main = 9;
			if ($midlist = $this->find('list', array('conditions'=>array('user_id'=>$uid, 'status'=>$main)))) {
				foreach ($midlist as $mid => $k) {
					$this->id = $mid;
					$this->save(array('status'=>1));
				}
			}
			$this->id = $id;
			$data = $this->save(array('status'=>$main));
		}
		return $data;
	}

	function getAllowTypes() {
		return array('image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png', 'image/gif');
	}

	function getAllowSize() {
		return 5120000;	
	}
	
	function small() {
		return 235;
	}

	function big() {
		return 580;
	}

	function getMaxSize() {
		return 580;
	}

}
?>
